/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package test.controllers;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import test.entities.Client;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import test.controllers.exceptions.IllegalOrphanException;
import test.controllers.exceptions.NonexistentEntityException;
import test.controllers.exceptions.PreexistingEntityException;
import test.entities.Action;
import test.entities.Entreprise;

/**
 *
 * @author Issam
 */
public class EntrepriseJpaController implements Serializable {

    public EntrepriseJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Entreprise entreprise) throws PreexistingEntityException, Exception {
        if (entreprise.getClientCollection() == null) {
            entreprise.setClientCollection(new ArrayList<Client>());
        }
        if (entreprise.getActionCollection() == null) {
            entreprise.setActionCollection(new ArrayList<Action>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Collection<Client> attachedClientCollection = new ArrayList<Client>();
            for (Client clientCollectionClientToAttach : entreprise.getClientCollection()) {
                clientCollectionClientToAttach = em.getReference(clientCollectionClientToAttach.getClass(), clientCollectionClientToAttach.getEmail());
                attachedClientCollection.add(clientCollectionClientToAttach);
            }
            entreprise.setClientCollection(attachedClientCollection);
            Collection<Action> attachedActionCollection = new ArrayList<Action>();
            for (Action actionCollectionActionToAttach : entreprise.getActionCollection()) {
                actionCollectionActionToAttach = em.getReference(actionCollectionActionToAttach.getClass(), actionCollectionActionToAttach.getNumAction());
                attachedActionCollection.add(actionCollectionActionToAttach);
            }
            entreprise.setActionCollection(attachedActionCollection);
            em.persist(entreprise);
            for (Client clientCollectionClient : entreprise.getClientCollection()) {
                Entreprise oldIdEntrepriseOfClientCollectionClient = clientCollectionClient.getIdEntreprise();
                clientCollectionClient.setIdEntreprise(entreprise);
                clientCollectionClient = em.merge(clientCollectionClient);
                if (oldIdEntrepriseOfClientCollectionClient != null) {
                    oldIdEntrepriseOfClientCollectionClient.getClientCollection().remove(clientCollectionClient);
                    oldIdEntrepriseOfClientCollectionClient = em.merge(oldIdEntrepriseOfClientCollectionClient);
                }
            }
            for (Action actionCollectionAction : entreprise.getActionCollection()) {
                Entreprise oldIdEntrepriseOfActionCollectionAction = actionCollectionAction.getIdEntreprise();
                actionCollectionAction.setIdEntreprise(entreprise);
                actionCollectionAction = em.merge(actionCollectionAction);
                if (oldIdEntrepriseOfActionCollectionAction != null) {
                    oldIdEntrepriseOfActionCollectionAction.getActionCollection().remove(actionCollectionAction);
                    oldIdEntrepriseOfActionCollectionAction = em.merge(oldIdEntrepriseOfActionCollectionAction);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findEntreprise(entreprise.getIdEntreprise()) != null) {
                throw new PreexistingEntityException("Entreprise " + entreprise + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Entreprise entreprise) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Entreprise persistentEntreprise = em.find(Entreprise.class, entreprise.getIdEntreprise());
            Collection<Client> clientCollectionOld = persistentEntreprise.getClientCollection();
            Collection<Client> clientCollectionNew = entreprise.getClientCollection();
            Collection<Action> actionCollectionOld = persistentEntreprise.getActionCollection();
            Collection<Action> actionCollectionNew = entreprise.getActionCollection();
            List<String> illegalOrphanMessages = null;
            for (Action actionCollectionOldAction : actionCollectionOld) {
                if (!actionCollectionNew.contains(actionCollectionOldAction)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Action " + actionCollectionOldAction + " since its idEntreprise field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Collection<Client> attachedClientCollectionNew = new ArrayList<Client>();
            for (Client clientCollectionNewClientToAttach : clientCollectionNew) {
                clientCollectionNewClientToAttach = em.getReference(clientCollectionNewClientToAttach.getClass(), clientCollectionNewClientToAttach.getEmail());
                attachedClientCollectionNew.add(clientCollectionNewClientToAttach);
            }
            clientCollectionNew = attachedClientCollectionNew;
            entreprise.setClientCollection(clientCollectionNew);
            Collection<Action> attachedActionCollectionNew = new ArrayList<Action>();
            for (Action actionCollectionNewActionToAttach : actionCollectionNew) {
                actionCollectionNewActionToAttach = em.getReference(actionCollectionNewActionToAttach.getClass(), actionCollectionNewActionToAttach.getNumAction());
                attachedActionCollectionNew.add(actionCollectionNewActionToAttach);
            }
            actionCollectionNew = attachedActionCollectionNew;
            entreprise.setActionCollection(actionCollectionNew);
            entreprise = em.merge(entreprise);
            for (Client clientCollectionOldClient : clientCollectionOld) {
                if (!clientCollectionNew.contains(clientCollectionOldClient)) {
                    clientCollectionOldClient.setIdEntreprise(null);
                    clientCollectionOldClient = em.merge(clientCollectionOldClient);
                }
            }
            for (Client clientCollectionNewClient : clientCollectionNew) {
                if (!clientCollectionOld.contains(clientCollectionNewClient)) {
                    Entreprise oldIdEntrepriseOfClientCollectionNewClient = clientCollectionNewClient.getIdEntreprise();
                    clientCollectionNewClient.setIdEntreprise(entreprise);
                    clientCollectionNewClient = em.merge(clientCollectionNewClient);
                    if (oldIdEntrepriseOfClientCollectionNewClient != null && !oldIdEntrepriseOfClientCollectionNewClient.equals(entreprise)) {
                        oldIdEntrepriseOfClientCollectionNewClient.getClientCollection().remove(clientCollectionNewClient);
                        oldIdEntrepriseOfClientCollectionNewClient = em.merge(oldIdEntrepriseOfClientCollectionNewClient);
                    }
                }
            }
            for (Action actionCollectionNewAction : actionCollectionNew) {
                if (!actionCollectionOld.contains(actionCollectionNewAction)) {
                    Entreprise oldIdEntrepriseOfActionCollectionNewAction = actionCollectionNewAction.getIdEntreprise();
                    actionCollectionNewAction.setIdEntreprise(entreprise);
                    actionCollectionNewAction = em.merge(actionCollectionNewAction);
                    if (oldIdEntrepriseOfActionCollectionNewAction != null && !oldIdEntrepriseOfActionCollectionNewAction.equals(entreprise)) {
                        oldIdEntrepriseOfActionCollectionNewAction.getActionCollection().remove(actionCollectionNewAction);
                        oldIdEntrepriseOfActionCollectionNewAction = em.merge(oldIdEntrepriseOfActionCollectionNewAction);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Short id = entreprise.getIdEntreprise();
                if (findEntreprise(id) == null) {
                    throw new NonexistentEntityException("The entreprise with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Short id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Entreprise entreprise;
            try {
                entreprise = em.getReference(Entreprise.class, id);
                entreprise.getIdEntreprise();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The entreprise with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Action> actionCollectionOrphanCheck = entreprise.getActionCollection();
            for (Action actionCollectionOrphanCheckAction : actionCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Entreprise (" + entreprise + ") cannot be destroyed since the Action " + actionCollectionOrphanCheckAction + " in its actionCollection field has a non-nullable idEntreprise field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Collection<Client> clientCollection = entreprise.getClientCollection();
            for (Client clientCollectionClient : clientCollection) {
                clientCollectionClient.setIdEntreprise(null);
                clientCollectionClient = em.merge(clientCollectionClient);
            }
            em.remove(entreprise);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Entreprise> findEntrepriseEntities() {
        return findEntrepriseEntities(true, -1, -1);
    }

    public List<Entreprise> findEntrepriseEntities(int maxResults, int firstResult) {
        return findEntrepriseEntities(false, maxResults, firstResult);
    }

    private List<Entreprise> findEntrepriseEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Entreprise.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Entreprise findEntreprise(Short id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Entreprise.class, id);
        } finally {
            em.close();
        }
    }
    
    public int getEntrepriseCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Entreprise> rt = cq.from(Entreprise.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
